from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.urls import reverse
from django.contrib.auth.hashers import make_password, check_password
from django.core.paginator import Paginator
from . import models
import time,os
# Create your views here.

def index(request):

	# return HttpResponse("后台首页")
	mag = "后台首页"
	return render(request,'myadmin/index.html',{"mag":mag})

def vipuser(request):

	#分页
    userinfo = models.Users.objects.all()
    # 实例化分页对象
    p = Paginator(userinfo, 10)
    #一共可以分多少页
    sumpage=p.num_pages
    # 取第几页的数据
     # 接受用户的页码
    page = int(request.GET.get('p',1))
    # 第几页的数据Response
    page1 = p.page(page)
    # 判断 如果用输入的页码<=3 显示前五个页码
    if page<=3:
        # 页码的迭代序列  [1,2,3,4,5,6,7]
        prange = p.page_range[:5]
    elif page+2>=sumpage:
        prange = p.page_range[-5:]
    else:
        prange = p.page_range[page-3:page+2]
    # 进行数据分配 通过 模板语法将数据展示到模板当中
    return render(request,'myadmin/table-list.html',{'userinfo':page1,'prange':prange,'page':page,'sumpage':sumpage})


def adduser(request):

	# return render(request,'myadmin/adduser.html')

	if request.method == "GET":
		return render(request,'myadmin/adduser.html')
	elif request.method == "POST":
		userinfo = request.POST.dict()
		userinfo.pop('csrfmiddlewaretoken')
		myfile = request.FILES.get("head_url",None)

		if not myfile:
			return HttpResponse("<script>alert('请选择头像');location.href=''</script>")

		userinfo['head_url'] = upload(myfile)

		userinfo['password'] = make_password(userinfo['password'],None,'pbkdf2_sha256')

		try:
			user = models.Users(**userinfo)
			user.save()
			return redirect(reverse('myadmin_vipuser'))
		except:
			return HttpResponse("<script>alert('添加失败');location.href=''</script>")

def upload(myfile):
	filename = str(time.time())+"."+myfile.name.split('.').pop()
	destination = open("./static/pics/"+filename,"wb+")
	for chunk in myfile.chunks():
		destination.write(chunk)
	destination.close()
	return '/static/pics'+filename

def deluser(request):
	 uid = request.GET.get('uid')
	 user = models.Users.objects.get(id=uid)
	 user.delete()
	 return redirect(reverse('myadmin_vipuser'))

def edituser(request):
	uid = request.GET.get('uid')
	print('this is uid',uid)
	if request.method == 'GET':
		user = models.Users.objects.get(id=uid)
		print('this is user:',user)
		return render(request,'myadmin/edit.html',{'user':user})
	elif request.method == 'POST':
		userinfo = request.POST.dict()
		uinfo = models.Users.objects.get(id=uid)
		uinfo.username = userinfo['username']
		uinfo.age = userinfo['age']
		uinfo.sex = userinfo['sex']

		file = request.FILES.get('head_url')
		if file:
			os.remove('.'+uinfo.head_url)
			headurl = upload(file)
			uinfo.head_url = headurl

		uinfo.save()
		return HttpResponse("<script>alert('修改成功');location.href='"+reverse('myadmin_vipuser')+"'</script>")

def upload(myfile):
	filename = str(time.time())+"."+myfile.name.split('.').pop()
	destination = open("./static/pics/"+filename,"wb+")
	for chunk in myfile.chunks():      
	    destination.write(chunk)  
	destination.close()
	# /static/pics/filename
	return '/static/pics/'+filename

def changes(request):
	uid = request.GET.get('id')
	status = request.GET.get('status')
	try:
		user = models.Users.objects.get(id=uid)
		user.status = int(status)
		user.save()
		msg = {"msg":"修改成功"}
		return JsonResponse(msg)
	except:
		msg = {"msg":"修改失败"}
		return JosnResponse(msg)

def respwd(request):
    # 接受uid
    uid = request.GET.get('uid')
    user = models.Users.objects.get(id=uid)
    user.password = make_password('123456', None, 'pbkdf2_sha256')
    user.save()

    data={'msg':'修改成功'}
    return JsonResponse(data)